//
//  Map.m
//  FleaFinder
//
//  Created by Hieu Le on 4/13/13.
//  Copyright (c) 2013 Kiwiweb. All rights reserved.
//

#import "Map.h"
#import "AddressAnnotation.h"
#import "CustomAnnotationView.h"
#import "GoogleMapXmlDataParser.h"
//#import "XmlParserMarkedListInCategory.h"
#import "MarkedInfo.h"

@interface Map ()

@end

@implementation Map

@synthesize theMap, locationManager;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

/*-(void) showAnnotationForLat: (double) lat andLng:(double) lng
{
    CLLocationCoordinate2D location;
    location.latitude = lat;
    location.longitude = lng;
    
    MKCoordinateRegion region;
    MKCoordinateSpan span;
    span.latitudeDelta=0.2;
    span.longitudeDelta=0.2;
    
    region.span=span;
    region.center=location;
    
    [theMap setRegion:region animated:TRUE];
    [theMap regionThatFits:region];
}*/

-(void) removeAllAnnotation
{
    if(theMap)
    {
        [theMap removeAnnotations:annotations];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    annotations = [NSMutableArray arrayWithCapacity:100];
    
    CGRect b = self.view.bounds;
    activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleGray];
    activityIndicator.alpha = 1.0;
    //indicator.frame = CGRectMake((b.size.width - 20) / 2, (b.size.height - 20) / 2, 20, 20);
    //center the indicator in the view
    //indicator.frame = CGRectMake((b.size.width - 20) / 2, (b.size.height - 20) / 2, 20, 20);
    activityIndicator.center = CGPointMake(b.size.width / 2, (b.size.height - activityIndicator.frame.size.height) / 2);
    [activityIndicator setHidesWhenStopped:YES];
    activityIndicator.color = [UIColor purpleColor];
    [self.view addSubview: activityIndicator];
    //[indicator release];
    
    
    appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    theMap.delegate = self;
    //locationDetected = NO;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
    askPermissionAlready = NO;
    isBackFromDetail = NO;
    
    longtitudeMeters = 20000;
    latitudeMeters = 20000;
}

-(void)viewWillAppear:(BOOL)animated
{
    if(!appDelegate){
        appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    }
    
    [self.locationManager setDelegate:self];
    
    //[self locateOnMap];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    if(!isBackFromDetail){
       
        [self removeAllAnnotation];
        
        [activityIndicator startAnimating];
        
        /*while(appDelegate.isLoadingMarketList){
            sleep(1);
        }*/
        
        /*[indicator stopAnimating];
         [indicator removeFromSuperview];
         indicator = nil;*/
        
        queueAddAnnotation = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queueAddAnnotation, ^{
            [annotations removeAllObjects];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self locateOnMap];
            });
            
            int stoppedAt = 0;
            Marked* m = nil;
            AddressAnnotation *addAnno = nil;
            
            BOOL allLoaded = NO;
            
            while(appDelegate.isLoadingLocation || !allLoaded){
                
                allLoaded = !appDelegate.isLoadingLocation;
                //NSLog(@"allLoaded = %d", allLoaded);
                //NSLog(@"size of marketListWithLocationLoaded = %d", [appDelegate.marketListWithLoadedLocation count]);
                for(int i = stoppedAt; i < [appDelegate.marketListWithLoadedLocation count]; ++i){
                    
                    m = [[appDelegate marketListWithLoadedLocation] objectAtIndex:i];
                    if(m.isLoadedLocation){
                        CLLocationCoordinate2D coordinate;
                        coordinate.longitude = m.longtitude;
                        coordinate.latitude = m.lattitude;
                        
                        addAnno = [[AddressAnnotation alloc] initWithCoordinate:coordinate];
                        addAnno.title = m.markedname;
                        addAnno.subtitle = [NSString stringWithFormat:@"%@ %@", m.road, m.city];
                        addAnno.marketId = m.marketId;
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [theMap addAnnotation:addAnno];
                            //NSLog(@"jus at 1 location");
                        });
                        [annotations addObject:addAnno];
                        //NSLog(@"showing annotation");
                    }
                    
                    stoppedAt = i + 1;
                }
                sleep(1);
            }
            
            //NSLog(@"exit thread checking location");
            dispatch_async(dispatch_get_main_queue(), ^{
                //if(activityIndicator && [activityIndicator isAnimating]){
                    [activityIndicator stopAnimating];
                //}
            });
            
        });
    }
    isBackFromDetail = NO;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setTheMap:nil];
    [super viewDidUnload];
}

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
    
    static NSString* identifier = @"currentloc";
    
    MKPinAnnotationView *annView = nil;
    
    annView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
    if(!annView){
        annView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
    }
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    
    if([annotation isKindOfClass:[AddressAnnotation class]]){
        AddressAnnotation* an = (AddressAnnotation*)annotation;
        
        if(an.marketId != -1){
            [btn addTarget:self action:@selector(clickButtonCallOut:) forControlEvents:UIControlEventTouchUpInside];
            btn.tag = ((AddressAnnotation*)annotation).marketId;
            
            annView.rightCalloutAccessoryView = btn;
            
            annView.pinColor = MKPinAnnotationColorPurple;
            
        } else {
            annView.pinColor = MKPinAnnotationColorRed;
        }
        
        annView.animatesDrop=TRUE;
        annView.canShowCallout = YES;
        annView.calloutOffset = CGPointMake(-5, 5);
    }
    return annView;
}

-(void) clickButtonCallOut:(id)sender
{
    // NSString *linkMarkedInfo;
    
    UIButton *btn = (UIButton*)sender;
    if(!appDelegate.markedInfoViewController){
        
        if(!appDelegate.storyBoard)
            appDelegate.storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
        
        appDelegate.markedInfoViewController = [appDelegate.storyBoard instantiateViewControllerWithIdentifier:@"SBMarkedInfo"];
    }
    
    [appDelegate.markedInfoViewController loadXmlData:appDelegate.common.linkMarkedInfo forMarket:btn.tag];
    [self.navigationController pushViewController:appDelegate.markedInfoViewController animated:YES];
    isBackFromDetail = YES;
}

-(void)locateOnMap
{
    BOOL ok = YES;
    [locationManager startUpdatingLocation];
    
    if([CLLocationManager locationServicesEnabled]){
        
        // Location Services Are Enabled
        
        switch([CLLocationManager authorizationStatus]){
            case kCLAuthorizationStatusAuthorized:
                // we can access location services
                //NSLog(@"ok");
                ok = YES;
                break;
            case kCLAuthorizationStatusDenied:
                // denied by user
                //NSLog(@"not ok");
                ok = NO;
                break;
            case kCLAuthorizationStatusRestricted:
                // restricted by parental controls
                ok = YES;
                break;
            case kCLAuthorizationStatusNotDetermined:
                // unable to determine, possibly disabled
                //NSLog(@"no no");
                ok = NO;
                break;
        }
    }else{
        // Location Services Are Disabled
        ok = NO;
    }
    
    if(!ok && !askPermissionAlready){
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Location Service Not Enabled" message:@"Please go to Settings > Privacy > Location > FleaFinder, and check ON to allow FleaFinder access you location." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
        
        askPermissionAlready = YES;
        
        return;
    }

    
//    [locationManager stopUpdatingLocation];
}

-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    [self.locationManager stopUpdatingLocation];
    CLLocation *location = [locations objectAtIndex:0];
    
    CLLocationCoordinate2D coordinate;
    //coordinate.longitude = googleMapXmlParser.lng;
    //coordinate.latitude = googleMapXmlParser.lat;
    coordinate.longitude = location.coordinate.longitude;
    coordinate.latitude = location.coordinate.latitude;
    
    //NSLog(@"%f ; %f", coordinate.longitude, coordinate.latitude);
    
    myLocation = [[AddressAnnotation alloc] initWithCoordinate:coordinate];
    myLocation.title = @"Nuværende lokation";
    myLocation.marketId = -1;
    [annotations addObject:myLocation];
    
    location = nil;
    
    [theMap addAnnotation:myLocation];
    
    CLLocationCoordinate2D noLocation = myLocation.coordinate;
    MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(noLocation, latitudeMeters, longtitudeMeters);
    MKCoordinateRegion adjustedRegion = [theMap regionThatFits:viewRegion];
    [theMap setRegion:adjustedRegion animated:YES];
    
    //[self loadAllMarkets];
    //[self addAnnotations:annotations];

}

@end
